package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author 李旭
 * @date 2021/10/27 15:43
 * @Description:
 *
 *  支付宝 支付
 */
@Controller
@RequestMapping("/api/payment/alipay")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;
    @Autowired
    private PaymentService paymentService;

    //统一收单 下单并支持接口
    @GetMapping("/submit/{orderId}")
    @ResponseBody
    public String submit(@PathVariable Long orderId){
        return alipayService.submit(orderId);
    }

    //同步回调    经过网关  （网关是对外（互联网进行暴露在外） ）
    //   http://api.gmall.com/api/payment/alipay/callback/return
    @GetMapping("/callback/return")
    public String callbackReturn(){
        return "redirect:" + AlipayConfig.return_order_url;
    }

    //异步回调    经过网关
    @PostMapping("/callback/notify")
    public String callbackNotify(@RequestParam Map<String, String> paramsMap){
        System.out.println(paramsMap.toString());

        /**
         * {gmt_create=2021-10-29 14:31:42,
         * charset=utf-8,
         * gmt_payment=2021-10-29 14:31:55,
         * notify_time=2021-10-29 14:31:56,
         * subject=Redmi K30 5G双模 120Hz流速屏 骁龙765G 30W快充 6GB+128GB 深海微光 游戏智能手机 小米 红米 Apple iPhone 11 (A2223) 64GB 红色 移动联,
         * sign=V4yotCaUYSC/oP8VPs4E9We6GjU8mntXu/vj/YjgAz3uyhC8td42CoZNlfl2TwxuoOVo9gzCs5U5OOOmt7zGVjqzhSuzbcZ/Xkm+j/K/LESy5ctbPLCncGF/x8Jz4K6ZzzMUdzAlMgozLyJL66lFsc8QKVXR4hHXMlTdUZf7o9l0iYUfghoAlL/fnP2PnMXTtJQBBlQ6a9yXPPnxut6KfeBAl2kKM1kI1AZ3+8aj1vdg3s3/8sfz25HTR+wbwUPQoTveR2tlenaZHbYNlD9Nu9k3EhW8IUJZEyEVONTbSoQfwm01XUhkddX6ufiG4CKQRVu4sWkFvCpUDxMa8cjumQ==,
         * buyer_id=2088102181130586,
         * invoice_amount=452214.00,
         * version=1.0,
         * notify_id=2021102900222143155030580518663905,
         * fund_bill_list=[
         *        {"amount":"452214.00",
         * 	"fundChannel":"ALIPAYACCOUNT"}
         * 	],
         * notify_type=trade_status_sync,
         * out_trade_no=ATGUIGU163513004877371345,
         * total_amount=452214.00,
         * trade_status=TRADE_SUCCESS,
         * trade_no=2021102922001430580501752383,
         * auth_app_id=2016102100732915,
         * receipt_amount=452214.00,
         * point_amount=0.00,
         * app_id=2016102100732915,
         * buyer_pay_amount=452214.00,
         * sign_type=RSA2,
         * seller_id=2088102180533564}
         *
         *
         *
         */
        //1:验签
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.charset, AlipayConfig.sign_type);
            if(signVerified){
                //校验签名成功
                //用户支付的金额是否正确 进行二次校验  用户付钱的金额是正确
                System.out.println("总金额：" + paramsMap.get("total_amount"));

                //订单的后续处理
                //1:交易是否成功
                String trade_status = paramsMap.get("trade_status");
                if("TRADE_SUCCESS".equals(trade_status)){
                    //2:金额是是否正确
                    PaymentInfo paymentInfo = paymentService.
                            selectPayment(paramsMap.get("out_trade_no"));
                    System.out.println(paymentInfo.getTotalAmount().toString());

                    String total_amount = paramsMap.get("total_amount");
                    if(paymentInfo.getTotalAmount().toString().equals(total_amount)){
                        //正确
                        //支付表 更新支付表
                        paymentService.updatePaymentInfo(paramsMap);
                        return "success";
                    }else{
                        System.out.println("金额不正确");
                        return "failure";//
                    }


                }else{
                    System.out.println("交易不成功");
                    return "failure";//
                }



            }else{
                //校验签名失败
                return "failure";//
            }

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "failure";//

    }
    //退款
    @GetMapping("/refund/{outTradeNo}")
    @ResponseBody
    public Result refund(@PathVariable String outTradeNo){

        alipayService.refund(outTradeNo);
        return Result.ok();
    }


}
